/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test_system.controller;

import java.io.File;
import test_system.menu.*;
import test_system.parser.*;
import test_system.questions.TestWrapper;
import test_system.user_logic.RestoreInfo;
import test_system.user_logic.Session;
import test_system.user_logic.SessionRestore;

/**
 *
 * @author root
 */
public class TestController {

    public static TestWrapper test;
    public static Session userSession;

    public void startTest() {
        Menu menu = new Menu(test, null);
        userSession = menu.avtorization();
        String[] userAnswers;
        if(isExistRestoreFile()){
            SessionRestore restorer = new SessionRestore();
            RestoreInfo info = restorer.restore(userSession.getUser().getLogin() + ".txt");
            test = info.getTest();
            userAnswers = new String[test.getTestLength()];
            replaseAnswers( userAnswers,info.getUserAnswers());
            userAnswers = menu.continuePooling(userAnswers, info.getUserAnswers().length);
        }else{
        StringBuffer testData = new ParserCSV().parseFile("/home/serji/Documents/qq.txt");
        System.out.println(testData);
        test = new ParseRefactor().createTest(testData);        
        userAnswers = menu.runTestDialog();
        }
        boolean[] userResult = checkUserAnswer(userAnswers);
        menu.markOutput(userResult);
    }
    
    private void replaseAnswers(String[] replaseObject, String[] replaseSubject){
        for(int i = 0; i < replaseObject.length; i++){
            System.out.print(replaseSubject.length);
            replaseSubject[i] = replaseObject[i];
        }
    }
    
    private boolean isExistRestoreFile(){
        String fileName = userSession.getUser().getLogin() + ".txt";
        File file = new File(fileName);
        return file.exists();
    }

    private boolean[] checkUserAnswer(String[] stringRes) {
        boolean[] checkedAnswers = new boolean[stringRes.length];
        for (int index = 0; index < stringRes.length; index++) {
            if (test.getQuestion(index).getClassName().equals("TextAnswerQuestion")) {
                checkedAnswers[index] = test.getQuestion(index).getRigthAnswer().toString().equals(stringRes[index]);
            } else {
                checkedAnswers[index] = test.getQuestion(index).getAnswerById(new Integer(stringRes[index]) - 1).isRight();
            }
        }        
        return checkedAnswers;
    }
    
}
